﻿using Inovout.Kuajing.Models;
using Inovout.Kuajing.Services;
using Inovout.Kuajing.Web.Models;
using Inovout.Web.Http;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;

namespace Inovout.Kuajing.Web.Controllers
{
    public class CommodityController : BaseHttpController
    {
        private CommodityService commodityService = ComponentRegistry.Resolve<CommodityService>();
        private PurchaseOrderService purchaseOrderService = ComponentRegistry.Resolve<PurchaseOrderService>();

        [Route("v1/commodity/{code}/AvailableSaleQuantity"), HttpGet]
        public JObject GetAvailableSaleQuantity(string code)
        {
            JObject result = new JObject();
            result["code"] = code;
            result["available_sale_quantity"] = this.commodityService.GetAvailableSaleQuantity(code);
            return result;
        }

        [Route("v1/commodity/purchase")]
        [HttpPost]
        public string Purchase(PurchaseOrder order)
        {
            purchaseOrderService.Create(order);
            var result = JsonConvert.SerializeObject(order, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });

            return result;
        }

        private Dictionary<string, string> csvCommodityColumns = new Dictionary<string, string>{
             {"Code","商品条码"},
            {"CategoryCode","商品编码"},
             {"Name","商品名称"},
            {"FeatureCode","规格编码"},
             {"FeatureName","规格名称"},
             {"SalePrice","售价"}
        };
        [Route("v1/commodity")]
        [HttpGet]
        public IEnumerable<Commodity> Get()
        {
            return this.commodityService.FindAll();
        }

        [Route("v1/commodity/mall/csv/{shipper}")]
        [HttpGet]
        public HttpResponseMessage MallCsv(string shipper)
        {
            StringBuilder sb = new StringBuilder();
            WriteCsv(sb, new List<string>(new string[]{"宝贝名称","仓库货号","宝贝类目","店铺类目","新旧程度","省","城市","出售方式","宝贝价格",
                "加价幅度","宝贝数量","有效期","运费承担","平邮","EMS","快递","发票","保修","放入仓库","橱窗推荐","开始时间","宝贝描述",
                "宝贝属性","邮费模版ID","会员打折","修改时间","上传状态","图片状态","返点比例","新图片","视频","销售属性组合","用户输入ID串"
            ,"用户输入名-值对","商家编码","销售属性别名","代充类型","数字ID","本地ID","宝贝分类","账户名称","宝贝状态","闪电发货","新品","食品专项",
            "尺码库","库存类型","库存计数","退换货承诺","物流体积","物流重量"}));
            IEnumerable<Commodity> commodities = commodityService.Query().Where(c=>c.ExternalShipperId==shipper);
            foreach (var commodity in commodities)
            {

        
                List<string> cells = new List<string>();
                cells.Add(commodity.Name);
                cells.Add(commodity.Code);
                cells.AddRange(new string[] { "", "", "1", "上海", "上海","1","149","","192","0","1","0","0","0","0","1","1","0","","记得修改我",
                    "1627743:3267186;1627745:29541;19166310:44702;19166829:41036269;42722636:3250994;1627207:107121;1627778:28388;1627778:672;1627778:28389;1627778:28390;1627778:28391;1627778:28392;1627778:28393","0","0","","200",
                    "2;2;2;2;","0","f6b9092afa56af767caaf40f07118542:1:0:|;b23debb841984cce7b596f99efa09564:1:1:|;27243ffd43967de42079dea5cae224f2:1:2:|;06cbdae708d6fe80927a2e8de223cbeb:2:0:1627207:107121|;"
                    ,"","149:10:56-26L38:1627207:107121;1627778:28388;149:30:56-26L39:1627207:107121;1627778:672;149:50:56-26L40:1627207:107121;1627778:28389;149:50:56-26L41:1627207:107121;1627778:28390;149:30:56-26L42:1627207:107121;1627778:28391;149:20:56-26L43:1627207:107121;1627778:28392;149:2:56-26L44:1627207:107121;1627778:28393;",
                    "\"200,001,632,501\"","\"AOG,DCG56-26\"","DCG56-26","1627207:107121:DCG56-26","0","0","0","1","meishi2004","2","0","0","","mysize_tp:-1","1728424528","0","0","","" });
                WriteCsv(sb, cells);
            }


            MemoryStream ms = new MemoryStream();
            byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF };
            ms.Write(bom, 0, bom.Length);
            byte[] buffer = UTF8Encoding.UTF8.GetBytes(sb.ToString());
            ms.Write(buffer, 0, buffer.Length);
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv" };
            var response = this.Request.CreateResponse(HttpStatusCode.OK);
            response.Content = content;
            return response;
        }
   

        [Route("v1/commodity/csv")]
        [HttpGet]
        public HttpResponseMessage List()
        {
            StringBuilder sb = new StringBuilder();
            WriteCsv(sb, csvCommodityColumns.Values.ToList());
            IEnumerable<Commodity> commodities = commodityService.FindAll();
            foreach (var commodity in commodities)
            {

                JObject commodityJObject = JObject.Parse(JsonConvert.SerializeObject(commodity, Formatting.Indented, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }));
                commodityJObject["SalePrice"] = 1000;

                List<string> cells = new List<string>();
                foreach (var key in csvCommodityColumns.Keys)
                {
                    string cell = commodityJObject[key].ToString();
                    cells.Add(cell);
                }
                WriteCsv(sb, cells);
            }


            MemoryStream ms = new MemoryStream();
            byte[] bom = new byte[] { 0xEF, 0xBB, 0xBF };
            ms.Write(bom, 0, bom.Length);
            byte[] buffer = UTF8Encoding.UTF8.GetBytes(sb.ToString());
            ms.Write(buffer, 0, buffer.Length);
            ms.Position = 0;
            HttpContent content = new StreamContent(ms);
            content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv" };
            var response = this.Request.CreateResponse(HttpStatusCode.OK);
            response.Content = content;
            return response;
        }
        private void WriteCsv(StringBuilder sb, List<String> cells)
        {
            string spe = ",";
            for (int i = 0; i < cells.Count; i++)
            {

                if (i > 0)
                {
                    sb.Append(spe);
                }

                sb.Append(cells[i]);

            }
            sb.AppendLine();
        }

    }
}
